var environment=_gl.environment||"production";
var ajaxUrl={
    "local":{
        "settimeoutTime":1400,
        "dataList":_gl._host_res+"/public/js/data/dataList.json",
        "delItem":_gl._host_res+"/public/js/data/delItem.json"
    },
    "production":{
        "settimeoutTime":0,
        "dataList":"",
        "delItem":""
    }
};
$(function(){
    var docrTable = null;
    var selectedArr = [];
    rendTable();
    //查询
    function searchData(data){
        var loadingIndex = _helper.fridayLoadinFun();
        //获取数据源
        setTimeout(function(){
            $.ajax({
                type: "POST",
                url:ajaxUrl[environment].dataList,
                data: data,
                dataType: "json"
            }).done(function(data) {
                if(data && data.code==200){
                    rendTable(data.data);
                }else{

                }
            }).fail(function(){
                layer.open({
                    icon:5,
                    title: '错误提示',
                    shade: 0,
                    content: '数据加载失败，请稍后重试！',
                    offset: 't'
                });
            }).always(function(){
                layer.close(loadingIndex);
            });
        },ajaxUrl[environment].settimeoutTime);
    }

    //审核优惠券
    function auditItem(data){
        gotoDetail({"flag":"audit","id":data["coupon-id"],"text":"审核优惠券"});
    }
    //查看优惠券
    function queryItem(data){
        gotoDetail({"flag":"query","id":data["coupon-id"],"text":"查看优惠券"});
    }
    //删除优惠券
    function delItem(data){
        layer.confirm('确定要删除该条优惠券码?', {icon: 3, title:'删除提示',offset: 't'}, function(index){
            layer.close(index);
            var loadingIndex = _helper.fridayLoadinFun();
            setTimeout(function(){
                $.ajax({
                    type: "POST",
                    url:ajaxUrl[environment].delItem,
                    data: data,
                    dataType: "json"
                }).done(function(data) {
                    if(data && data.code==200){
                        layer.msg("删除成功！",{time:1500,offset: 't'});
                    }else{
                        layer.msg((data&&data.message)||"删除失败！",{time:1500,offset: 't'});
                    }
                }).fail(function(){
                    layer.open({
                        icon:5,
                        title: '错误提示',
                        shade: 0,
                        content: '删除失败，请稍后再试！',
                        offset: 't'
                    });
                }).always(function(){
                    layer.close(loadingIndex);
                });
            },ajaxUrl[environment].settimeoutTime);
        });
    }

    //渲染table
    function rendTable(data){
        docrTable = $('#example').dataTable({
            "destroy": true,
            "bProcessing" : true, //DataTables载入数据时，是否显示‘进度’提示
            "bStateSave" : true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            //"sScrollY" : 450, //DataTables的高
            //"sScrollX" : 820, //DataTables的宽
            "bPaginate" : true, //是否显示（应用）分页器
            "sPaginationType" : "full_numbers", //详细分页组，可以支持直接跳转到某页
            "aLengthMenu" : [5, 10, 20, 100], //更改显示记录数选项
            "iDisplayLength" : 5, //默认显示的记录数
            "bAutoWidth" : true, //是否自适应宽度
            "bScrollCollapse" : true, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变

            "bInfo" : true, //是否显示页脚信息，DataTables插件左下角显示记录数
            "bSort" : true, //是否启动各个字段的排序功能
            "aaSorting" : [[1, "desc"]], //默认的排序方式，第2列，升序排列
            "bFilter" : true, //是否启动过滤、搜索功能
            "sDom": '<"friday"<"friday-33"l><"friday-33"f><"friday-33"<"btn-list">>><"friday"<"friday-100"tr>><"friday"<"friday-50"i><"friday-50"p>>',//
            "oLanguage": { //国际化配置
                "sProcessing" : "正在获取数据，请稍后...",
                "sLengthMenu" : "每页显示 _MENU_ 条",
                "sZeroRecords" : "没有您要搜索的内容",
                "sInfo" : "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条",
                "sInfoEmpty" : "记录数为0",
                "sInfoFiltered" : "(全部记录数 _MAX_ 条)",
                "sInfoPostFix" : "",
                "sSearch" : "搜索",
                "sUrl" : "",
                "oPaginate": {
                    "sFirst" : "首页",
                    "sPrevious" : "上一页",
                    "sNext" : "下一页",
                    "sLast" : "尾页"
                }
            },
            "data": data,
            "aoColumns"         : [
                {
                    "sTitle"     : '<input class=\"checkbox_eula\" id=\"checkbox_id_all\" name=\"checkbox_name_all\" type=\"checkbox\" value=\"\">',
                    "sClass"     : "text-center td-middle",
                    "bSortable" : false,
                    "sWidth"     : "2%",
                    "data"        : null,
                    "mRender": function ( data, type, full ) {
                        return '<input class="checkbox_eula" type="checkbox" value="">';
                    }
                },
                {
                    "sTitle"     : "序号",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : false,
                    "sWidth"     : "6%",
                    "data"        : null,
                    "targets"    : 1
                },
                {
                    "mDataProp" : "coupon-id",
                    "sDefaultContent" : "", //此列默认值为""，以防数据中没有此值，DataTables加载数据的时候报错
                    "bVisible" : false //此列不显示
                },
                {
                    "sTitle"     : "券名称",
                    "mDataProp" : "coupon-name",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : true,
                    "sWidth"     : "16%"
                },{
                    "sTitle"     : "券类型",
                    "mDataProp" : "coupon-type",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : true,
                    "sWidth"     : "10%"
                },{
                    "sTitle"     : "有效期",
                    "mDataProp" : "valid-from-date-start",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : true,
                    "sWidth"     : "16%"
                },{
                    "sTitle"     : "创建人",
                    "mDataProp" : "create-person",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : true,
                    "sWidth"     : "10%"
                },{
                    "sTitle"     : "创建日期",
                    "mDataProp" : "create-date",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : true,
                    "sWidth"     : "14%"
                },{
                    "sTitle"     : "状态",
                    "mDataProp" : "state",
                    "sClass"     : "dt-center td-middle",
                    "bSortable" : true,
                    "sWidth"     : "10%"
                },{
                    "sTitle"     : "操作",
                    "sClass"     : "dt-center td-middle",
                    "data"       : null,
                    "bSortable" : false,
                    "sWidth"     : "16%",
                    "mRender": function ( data, type, full ) {
                        return '<a class="btn btn-primary btn-sm btn-operation btn-audit" href="#"><span class="glyphicon glyphicon-check"></span>审核</a><a class="btn btn-success btn-sm btn-operation btn-query" href="#"><span class="glyphicon glyphicon-search"></span>查看</a>';
                    }
                }
            ],
            "fnInitComplete": function(oSettings, json) {   //datatables初始化完毕后会调用这个方法
                //console.log("fnInitComplete");

            },
            "fnPreDrawCallback": function( oSettings ) {   //每一次绘datatables时候调用的方法
                //console.log("fnPreDrawCallback");
            },
            "fnDrawCallback"    : function(){  //重绘的回调函数
                //console.log("fnDrawCallback");
                this.api().column(1).nodes().each(function(cell, i) {
                    cell.innerHTML =  i + 1;
                });
                checkboxInit();

                /* 审核*/
                $('a.btn-audit').on( 'click', function (e) {
                    e.stopPropagation();
                    var data = $('#example').DataTable().row($(this).parents('tr')).data();
                    auditItem(data);
                } );
                /*查看*/
                $('a.btn-query').on( 'click', function (e) {
                    e.stopPropagation();
                    var data = $('#example').DataTable().row($(this).parents('tr')).data();
                    queryItem(data);
                } );
            },
            "fnRowCallback": function( row, data ) {//添加单击事件，改变行的样式
                //if ( $.inArray(data.DT_RowId, selectedArr) !== -1 ) {
                //    $(row).addClass('selected');
                //}

            },
            "fnCreatedRow": function(nRow, aData, iDataIndex) {
                if ( aData["state"] == 1 ){
                    $('td:eq(7)', nRow).html( '待审核' );
                }else if ( aData["state"] == 2 ){
                    $('td:eq(7)', nRow).html( '已审核' );
                }else{
                    $('td:eq(7)', nRow).html( '--' );
                }
            }
        });
        //var alldata=$('#example').dataTable().fnGetData();//得到页面中所有对象
        //http://www.cnblogs.com/amoniyibeizi/p/4548111.html
        $("div.btn-list").html('<button type="button" class="btn btn-success btn-add">新增优惠券</button><button type="button" class="btn btn-success btn-del">批量删除</button>');

        /*批量删除*/
        $('button.btn-del').on( 'click', function () {
            var arr = getChecedTr();
            if(arr.length==0){
                layer.msg("请选中一条数据！",{time:1500,offset: 't'});
                return false;
            }
            var obj={};
            obj.id="";
            $.each(arr,function(index,item){
                if(index>0){
                    obj.id+="|";
                }
                obj.id+=item["coupon-id"];
            });
            delItem(obj);
        } );
        /*新增优惠券*/
        $('button.btn-add').on( 'click', function () {
            gotoDetail({"flag":"add","text":"新增优惠券"});
        } );
    }

    //查询
    $(".btn-search").on("click",function(e){
        e.stopPropagation();
        searchData(_helper.getParameter("searchForm"));
    });
    //更多
    $(".btn-more").on("click",function(e){
        e.stopPropagation();
        var $glyphicon = $(this).find(".glyphicon");
        if($glyphicon.hasClass("glyphicon-chevron-down")){
            $glyphicon.removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
        }else{
            $glyphicon.removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
        }
        $(".query-list").slideToggle();
    });

    //获取被选择的行
    function getChecedTr(){
        var selectedData =[];
        var table = $('#example').DataTable();
        var rows = table.rows('.selected').indexes();
        var data = table.rows(rows).data();
        for(var i=0;i<data.length;i++){
            selectedData.push(data[i]);
        }
        return selectedData;
    }

    //复选框初始化,全选,单击行，改变行的样式
    function checkboxInit(){
        //初始化checkbox
        $(".checkbox_eula").iCheck({
            checkboxClass: "icheckbox_squaremini-blue"
        },function(){
            console.log("6");
        });

        $("#checkbox_id_all").iCheck('uncheck');

        $('.checkbox_eula').on("ifChecked",function(){
            var $this = $(this);
            if($this.attr("id")!="checkbox_id_all"){
                $this.parents("tr").addClass("selected");

                var $checkbox_id_allChecked = $("#checkbox_id_all").prop("checked");
                var $trLen = $this.parents("tbody").find("tr").length;
                var $checkboxCheckedLen = $this.parents("tbody").find("input[type='checkbox']:checked").length;
                if(!$checkbox_id_allChecked && $trLen == $checkboxCheckedLen){
                    $("#checkbox_id_all").iCheck('check');
                }
            }else{
                var $tbody = $this.parents("thead").siblings("tbody");
                $tbody.find("input[type='checkbox']:not(:checked)").parents("tr").addClass("selected").find(".checkbox_eula").iCheck('check');
            }
        });
        $('.checkbox_eula').on("ifUnchecked",function(){
            var $this = $(this);
            if($this.attr("id")!="checkbox_id_all"){
                $this.parents("tr").removeClass("selected");

                var $checkbox_id_allChecked = $("#checkbox_id_all").prop("checked");
                var $trLen = $this.parents("tbody").find("tr").length;
                var $checkboxCheckedLen = $this.parents("tbody").find("input[type='checkbox']:checked").length;
                if($checkbox_id_allChecked && $trLen != $checkboxCheckedLen){
                    var $tbody = $this.parents("tbody");
                    var arr=[];
                    $tbody.find("tr").each(function(){
                        arr.push($(this).hasClass("selected"));
                    });
                    $("#checkbox_id_all").iCheck('uncheck');
                    $tbody.find("tr").each(function(index,item){
                        if(arr[index]){
                            $(this).find(".checkbox_eula").iCheck('check');
                        }else{
                            $(this).find(".checkbox_eula").iCheck('uncheck');
                        }
                    });
                }
            }else{
                var $tbody = $this.parents("thead").siblings("tbody");
                $tbody.find("input[type='checkbox']:checked").parents("tr").removeClass("selected").find(".checkbox_eula").iCheck('uncheck');
            }
        });

        /**
         * 单击行，选中复选框
         */
        $("#example tr").slice(1).each(function(g){
            $(this).children().slice(1).click(function(){
                $(this).parents("tr").find(".checkbox_eula").iCheck('toggle');
            });
        });
    }

    //进入编辑页面
    function gotoDetail(obj){
        parent.addNewIframe({"href":"views/order/detail.html?flag="+((obj&&obj.flag)||add)+"&id="+((obj&&obj.id)||""),"text":(obj&&obj.text)||"审核优惠券"});
    }
});